package com.itheima.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @className:ErrorMessageConfig
 * @date: 2025/7/14 下午3:52
 * @description:
 */
@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled",havingValue = "true")
//@ConditionalOnProperty 是 Spring Boot 提供的一个条件注解，用于控制 Bean 的创建条件。
// 当指定的配置属性满足特定值时，被该注解标注的组件才会被加载到 Spring 容器中。
public class ErrorMessageConfig {
    @Bean
    public DirectExchange errorDirectExchange() {
        return new DirectExchange("error.direct");
    }
    @Bean
    public Queue errorDirectQueue() {
        return new Queue("error.queue",true);
    }

    @Bean
    public Binding errorDirectBinding() {
        return BindingBuilder.bind(errorDirectQueue()).to(errorDirectExchange()).with("error");
    }

    /**
     * 失败重试策略RepublishMessageRecoverer配置
     * 重试耗尽后，将失败消息投递到指定的交换机
     * @param rabbitTemplate
     * @return
     */
    @Bean
    public MessageRecoverer errorMessageConverter(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error");
    }
}
